package top.yaofengqiao.springcloudsimple.web.starter.security;


import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import top.yaofengqiao.springcloudsimple.auth.api.IAuthDubboService;
import top.yaofengqiao.springcloudsimple.auth.api.dto.TokenAuthResultDTO;

import java.time.Duration;

/**
 * @author yfq
 * @date 2024/6/18 13:10
 * @description
 */
@Slf4j
public class TokenCache {
    @DubboReference
    private IAuthDubboService authDubboService;

    private final LoadingCache<String, TokenAuthResultDTO> tokenCache = CacheBuilder.newBuilder()
            .refreshAfterWrite(Duration.ofMinutes(1))
            .build(new CacheLoader<String, TokenAuthResultDTO>() {
                @Override
                public TokenAuthResultDTO load(String key) {
                    return authDubboService.authentication(key);
                }
            });

    public TokenAuthResultDTO getToken(String token) {
        try {
            return tokenCache.get(token);
        } catch (Exception e) {
            log.error("token信息获取错误：token：{}", token, e);
            return null;
        }
    }
}
